﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Mono.Options;

namespace octalforty.Componento.Commands
{
    [Command("help", Aliases = "h")]
    public class HelpCommand : ICommand
    {
        private readonly Func<IEnumerable<ICommand>> commandsFactory;

        public HelpCommand(Func<IEnumerable<ICommand>> commandsFactory)
        {
            this.commandsFactory = commandsFactory;
        }

        public OptionSet GetOptionSet(object options)
        {
            throw new NotImplementedException();
        }

        public void Execute(string[] args)
        {
            //
            // "co help" displays a list of all commands
            if(args.Length == 0)
            {
                var commands = from c in commandsFactory.Invoke() select c;
                foreach(var c in commands)
                {
                    var commandAttribute = ((CommandAttribute)c.GetType().GetCustomAttributes(typeof(CommandAttribute), false)[0]);
                    Console.WriteLine(commandAttribute.Name);
                } // foreach
            } // if
            else
            {
                var commands =
                    from c in commandsFactory.Invoke()
                    let a = ((CommandAttribute)c.GetType().GetCustomAttributes(typeof(CommandAttribute), false)[0])
                    where a.Name.ToLowerInvariant() == args[0] || (!string.IsNullOrEmpty(a.Aliases) && a.Aliases.ToLowerInvariant().Split(';').Contains(args[0]))
                    select new { c, a };
                var command = commands.Single();

                Console.WriteLine(command.a.Description);
                command.c.GetOptionSet(null).WriteOptionDescriptions(Console.Out);
            } // else
        }
    }
}
